package com.glink.manage.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.nacos.common.utils.Objects;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.glink.common.contants.BaseCodeConstants;
import com.glink.common.exception.GeneralSimpleException;
import com.glink.common.util.BaseCommonUtils;
import com.glink.manage.common.PoiTools;
import com.glink.manage.common.enums.WorkStatusSeqDict;
import com.glink.manage.domain.ConstructionWorkBean;
import com.glink.manage.domain.ConstructionWorkUnitRelaBean;
import com.glink.manage.dto.constructionwork.*;
import com.glink.manage.mapper.ConstructionWorkMapper;
import com.glink.manage.service.*;
import com.glink.manage.vo.code.CodeVO;
import com.glink.manage.vo.constructionwork.ConstructionWorkBaseVO;
import com.glink.manage.vo.constructionwork.ConstructionWorkExportVO;
import com.glink.manage.vo.constructionwork.ConstructionWorkListVO;
import com.glink.manage.vo.constructionwork.ConstructionWorkPageVO;
import com.glink.manage.vo.participatingunit.ParticipatingUnitSimpleInfoVO;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author qiushaoshan
 * @since 2025-01-08
 */
@Service
@Slf4j
public class ConstructionWorkServiceImpl extends ServiceImpl<ConstructionWorkMapper, ConstructionWorkBean> implements ConstructionWorkService {

    @Autowired
    private ConstructionWorkUnitRelaService constructionWorkUnitRelaService;

    @Autowired
    private ConstructionWorkSiteService constructionWorkSiteService;
    
    @Autowired
    @Lazy
    private ConstructionWorkService constructionWorkService;
    
    @Autowired
    private CodeService codeService;

    @Autowired
    @Lazy
    private PersonManageService personManageService;

    @Autowired
    private OrgService orgService;

    @Autowired
    @Lazy
    private UserService userService;


    /**
     * 保存施工工程
     *
     * @param dto 保存信息
     * @return 保存状态
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean saveConstructionWork(ConstructionWorkSaveDTO dto) {
        ConstructionWorkBean constructionWorkBean = new ConstructionWorkBean();
        BeanUtils.copyProperties(dto, constructionWorkBean);

        constructionWorkBean.setObjId(BaseCommonUtils.generateUUID());

        constructionWorkBean.setSeq(getWorkSeq(dto.getStatus()));

        return save(constructionWorkBean);
    }

    /**
     * 获取工程序号
     *
     * @param status 状态
     * @return 排序
     */
    private Integer getWorkSeq(String status) {
        Integer seq = 0;
        switch (status) {
            case BaseCodeConstants.CodeType_ConstructionStatus.KEY_ConstructionStatus01:
                seq = WorkStatusSeqDict.UNDER_CONSTRUCTION.getKey();
                break;
            case BaseCodeConstants.CodeType_ConstructionStatus.KEY_ConstructionStatus02:
                seq = WorkStatusSeqDict.COMPLETED.getKey();
                break;
            case BaseCodeConstants.CodeType_ConstructionStatus.KEY_ConstructionStatus03:
                seq = WorkStatusSeqDict.SHUTDOWN.getKey();
                break;
            case BaseCodeConstants.CodeType_ConstructionStatus.KEY_ConstructionStatus04:
                seq = WorkStatusSeqDict.NOT_START.getKey();
                break;
        }

        return seq;
    }

    /**
     * 更新施工工程
     *
     * @param dto 更新信息
     * @return 更新状态
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean updateConstructionWork(ConstructionWorkUpdateDTO dto) throws GeneralSimpleException {
        ConstructionWorkBean constructionWorkBean = this.getById(dto.getObjId());
        if (Objects.isNull(constructionWorkBean)) {
            throw new GeneralSimpleException("500002", dto.getObjId());
        }

        BeanUtils.copyProperties(dto, constructionWorkBean);

        constructionWorkBean.setSeq(getWorkSeq(dto.getStatus()));

        return updateById(constructionWorkBean);
    }

    /**
     * 根据ID查询施工工程信息
     *
     * @param workIdDTO 施工工程ID
     * @return 施工工程信息
     */
    @Override
    public ConstructionWorkBaseVO findById(ConstructionWorkIdDTO workIdDTO) throws GeneralSimpleException {
        ConstructionWorkBean constructionWorkBean = this.getById(workIdDTO.getObjId());
        if (Objects.isNull(constructionWorkBean)) {
            throw new GeneralSimpleException("500002", workIdDTO.getObjId());
        }
        ConstructionWorkBaseVO baseVO = new ConstructionWorkBaseVO();
        BeanUtils.copyProperties(constructionWorkBean, baseVO);

        if (StringUtils.isNotBlank(baseVO.getProjectDepartmentObjId())) {
            baseVO.setProjectDepartmentObjName(orgService.findOrgNameByOrgId(baseVO.getProjectDepartmentObjId()));
        }

        // 负责人
        if (StringUtils.isNotBlank(baseVO.getSuperintendent())) {
            baseVO.setSuperintendentName(personManageService.findNameByObjId(baseVO.getSuperintendent()));
        }

        return baseVO;
    }

    /**
     * 分页查询施工工程
     *
     * @param dto 分页查询条件
     * @return 施工工程
     * @throws GeneralSimpleException
     */
    @Override
    public IPage<ConstructionWorkPageVO> findByPage(ConstructionWorkPageDTO dto) throws GeneralSimpleException {
        IPage<ConstructionWorkBean> constructionWorkBeanIPage = new Page<>(dto.getPage(), dto.getSize());

        LambdaQueryChainWrapper<ConstructionWorkBean> pageLambda = getPageLambda(dto.getWorkName(), dto.getStatusList());
        if(pageLambda == null){
            return new Page<>(dto.getPage(), dto.getSize());
        }
        IPage<ConstructionWorkBean> workBeanIPage = pageLambda.page(constructionWorkBeanIPage);

        IPage<ConstructionWorkPageVO> pageVOIPage = new Page<>(workBeanIPage.getCurrent(), workBeanIPage.getSize(), workBeanIPage.getTotal());
        List<ConstructionWorkPageVO> pageVOList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(workBeanIPage.getRecords())) {
            workBeanIPage.getRecords().forEach(constructionWorkBean -> {
                ConstructionWorkPageVO workPageVO = new ConstructionWorkPageVO();
                BeanUtils.copyProperties(constructionWorkBean, workPageVO);

                // 参建单位
                workPageVO.setUnitCount(constructionWorkUnitRelaService.countByConstructionWorkObjId(constructionWorkBean.getObjId()));

                // 工程现场
                workPageVO.setSiteCount(constructionWorkSiteService.countByConstructionWorkObjId(constructionWorkBean.getObjId()));

                // 负责人名称
                if (StringUtils.isNotBlank(constructionWorkBean.getSuperintendent())) {
                    workPageVO.setSuperintendentName(personManageService.findNameByObjId(constructionWorkBean.getSuperintendent()));
                }
                pageVOList.add(workPageVO);
            });
            pageVOIPage.setRecords(pageVOList);
        }
        return pageVOIPage;
    }

    /**
     * 根据条件组装分页的lambda
     *
     * @param workName   施工工程名称
     * @param statusList 建设状态
     * @return lambda
     */
    private LambdaQueryChainWrapper<ConstructionWorkBean> getPageLambda(String workName, List<String> statusList) throws GeneralSimpleException {
        boolean headOffice = userService.checkHeadOffice();
        List<String> dataPermissionOrgIdList = null;
        if (!headOffice) {
            dataPermissionOrgIdList = orgService.getDataPermissionOrgId();
            if(CollectionUtils.isEmpty(dataPermissionOrgIdList)){
                return null;
            }
        }
        return this.lambdaQuery()
                .in(!headOffice && CollectionUtils.isNotEmpty(dataPermissionOrgIdList), ConstructionWorkBean::getProjectDepartmentObjId, dataPermissionOrgIdList)
                .like(StringUtils.isNotEmpty(workName), ConstructionWorkBean::getWorkName, workName)
                .in(CollectionUtils.isNotEmpty(statusList), ConstructionWorkBean::getStatus, statusList)
                .orderByAsc(ConstructionWorkBean::getSeq)
                .orderByAsc(ConstructionWorkBean::getWorkName)
                .orderByAsc(ConstructionWorkBean::getObjId)
                ;
    }

    @Override
    public void exportExcel(ConstructionWorkExportDTO dto, HttpServletResponse response) throws Exception {

        List<ConstructionWorkExportVO> expVOList = Lists.newArrayList();
        LambdaQueryChainWrapper<ConstructionWorkBean> pageLambda = getPageLambda(dto.getWorkName(), dto.getStatusList());
        if(pageLambda == null){
            return;
        }
        List<ConstructionWorkBean> constructionWorkBeanList = pageLambda.list();
        if (CollectionUtils.isNotEmpty(constructionWorkBeanList)) {

            List<CodeVO> typeList = codeService.findByTypeList(Collections.singletonList(BaseCodeConstants.CodeType_01.KEY_ConstructionStatus));
            Map<String, String> constructionStatusMap = Maps.newHashMap();
            if (CollectionUtils.isNotEmpty(typeList)) {
                typeList.forEach(type -> constructionStatusMap.put(type.getKey(), type.getName()));
            }

            constructionWorkBeanList.forEach(constructionWorkBean -> {
                ConstructionWorkExportVO exportVO = new ConstructionWorkExportVO();
                BeanUtils.copyProperties(constructionWorkBean, exportVO);

                // 建设状态
                if (StringUtils.isNotBlank(exportVO.getStatus()) && constructionStatusMap.containsKey(exportVO.getStatus())) {
                    exportVO.setStatus(constructionStatusMap.get(exportVO.getStatus()));
                } else {
                    exportVO.setStatus("");
                }

                // 开始时间
                if (Objects.nonNull(constructionWorkBean.getPlannedDurationStart())) {
                    exportVO.setPlannedDuration(BaseCommonUtils.DATE_FORMAT_DAY_3.format(constructionWorkBean.getPlannedDurationStart()));
                }

                // 结束时间
                if (Objects.nonNull(constructionWorkBean.getPlannedDurationEnd())) {
                    if (StringUtils.isNotBlank(exportVO.getPlannedDuration())) {
                        exportVO.setPlannedDuration(exportVO.getPlannedDuration() + "~" + BaseCommonUtils.DATE_FORMAT_DAY_3.format(constructionWorkBean.getPlannedDurationEnd()));
                    } else {
                        exportVO.setPlannedDuration(BaseCommonUtils.DATE_FORMAT_DAY_3.format(constructionWorkBean.getPlannedDurationEnd()));
                    }
                }

                // 参建单位
//                Integer unitCount = constructionWorkUnitRelaService.countByConstructionWorkObjId(constructionWorkBean.getObjId());
//                if(Objects.nonNull(unitCount)){
//                    exportVO.setUnitCount(String.valueOf(unitCount));    
//                }
//                
//                // 工程现场
//                Integer siteCount = constructionWorkSiteService.countByConstructionWorkObjId(constructionWorkBean.getObjId());
//                if(Objects.nonNull(siteCount)){
//                    exportVO.setSiteCount(String.valueOf(siteCount));
//                }

                expVOList.add(exportVO);
            });
        }

        exportExcel(expVOList, response);
    }

    public void exportExcel(List<ConstructionWorkExportVO> exportVOList, HttpServletResponse response) {
        // 创建新的Excel 工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 在Excel工作簿中建一工作表，其名为缺省值
        XSSFSheet sheet = workbook.createSheet();

        try {
            //添加数据
            for (int rowNum = 1; rowNum <= exportVOList.size(); rowNum++) {
                ConstructionWorkExportVO exportVO = exportVOList.get(rowNum - 1);
                Map<String, Object> excelVOMap = BeanUtil.beanToMap(exportVO);
                //内容
                Object[] keySet = excelVOMap.keySet().toArray();
                //创建表头
                if (rowNum == 1) {
                    // 表头
                    XSSFRow row = sheet.createRow(0);
                    for (int i = 0; i < keySet.length; i++) {
                        String key = keySet[i].toString();
                        XSSFCell cell = row.createCell(i);
                        cell.setCellStyle(getCellStyle(workbook));
                        cell.setCellValue(key);
                        sheet.setColumnWidth(i, 30 * 180);
                    }
                }
                // 内容
                XSSFRow r = sheet.createRow(rowNum);
                Object[] valueCollection = excelVOMap.values().toArray();
                for (int cellNum = 0; cellNum < valueCollection.length; cellNum++) {
                    if (cellNum == 0) {
                        XSSFCell cell = r.createCell(cellNum);
                        cell.setCellStyle(getCellStyle(workbook));
                        cell.setCellValue(rowNum);
                    } else { // if(cellNum != valueCollection.length - 1)
                        XSSFCell cell = r.createCell(cellNum);
                        cell.setCellStyle(getCellStyle(workbook));
                        cell.setCellValue(java.util.Objects.isNull(valueCollection[cellNum]) ? Strings.EMPTY : valueCollection[cellNum].toString());
                    }/*else{
                        //下载图片
                        Object rendering = valueCollection[cellNum];
                        if (Objects.nonNull(rendering) && StringUtils.isNotBlank(rendering.toString())) {
                            String renderingStr = rendering.toString();
                            String[] renderings = renderingStr.split(",", -1);
                            for (int i = 0; i < renderings.length; i++) {
                                byte[] fileByte = attachmentService.getFileByte(renderings[i]);
                                //将图片插入到单元格中
                                if (Objects.nonNull(fileByte)) {
                                    r.setHeight((short) (20 * 100));
                                    sheet.setColumnWidth(cellNum + i, 30 * 180);
                                    writePic(fileByte, workbook, sheet, rowNum, cellNum + i);
                                }
                            }
                        }
                    }*/
                }
            }

            String ret = System.getProperty("user.dir") + "/" + System.currentTimeMillis() + ".xlsx";
            PoiTools.write2Disk(workbook, ret);
            String fileName = FilenameUtils.getName(ret);
            PoiTools.exportExcelFile(ret, fileName, response);
        } catch (Exception e) {
            log.error("excel写入失败：{}", e.getMessage(), e);
        }
    }

    private static void writePic(byte[] fileByte, Workbook workbook, XSSFSheet sheet, int row, int col) {
        XSSFDrawing drawing = sheet.createDrawingPatriarch();
        int pictureIndex = workbook.addPicture(fileByte, Workbook.PICTURE_TYPE_PNG);

        XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, col, row, col + 1, row + 1);
        anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);

        drawing.createPicture(anchor, pictureIndex);
    }


    private static CellStyle getCellStyle(XSSFWorkbook workbook) {
        // 创建一个单元格样式，用于设置文本居中
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER); // 设置水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER); // 设置垂直居中
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        return style;
    }

    /**
     * 查询参建单位列表
     *
     * @param dto 施工工程信息
     * @return 参建单位
     */
    @Override
    public IPage<ParticipatingUnitSimpleInfoVO> findUnitByPage(ConstructionWorkUnitPageDTO dto) {

        return constructionWorkUnitRelaService.findUnitByPage(dto);
    }

    /**
     * 餐具工程ID查询工程名称
     *
     * @param constructionWorkObjId 工程ID
     * @return 工程名称
     */
    @Override
    public String findNameByObjId(String constructionWorkObjId) {
        ConstructionWorkBean constructionWorkBean = this.lambdaQuery().eq(ConstructionWorkBean::getObjId, constructionWorkObjId).one();
        if (Objects.nonNull(constructionWorkBean)) {
            return constructionWorkBean.getWorkName();
        }
        return null;
    }

    /**
     * 根据工程ID查询排出后的工程信息 准入查询
     *
     * @param constructiuonWorkObjIdList 工程ID
     * @return 工程信息
     */
    @Override
    public List<ConstructionWorkListVO> findPendingAdmissionListByObjIdNotIn(List<String> constructiuonWorkObjIdList) throws GeneralSimpleException {

        boolean department = orgService.checkDepartment();
        boolean participatingUnit = false;
        List<String> dataPermissionDepartmentOrgIdList = Lists.newArrayList();
        List<String> workIdList = Lists.newArrayList();
        if (department) {
            dataPermissionDepartmentOrgIdList = orgService.getDataPermissionDepartmentOrgId();
        } else {
            String orgId = BaseCommonUtils.extractOrdIdByToken();
            if (StringUtils.isBlank(orgId)) {
                throw new GeneralSimpleException("100003");
            }
            participatingUnit = orgService.checkParticipatingUnitByOrgId(orgId);
            if (participatingUnit) {
                workIdList = constructionWorkUnitRelaService.findWorkIdByUnitId(orgId);
            }
            if (CollectionUtils.isEmpty(workIdList)) {
                // 该参建单位没有关联的工程，因此直接返回
                return null;
            }
        }

        List<ConstructionWorkBean> constructionWorkBeanList = this.lambdaQuery()
                .notIn(CollectionUtils.isNotEmpty(constructiuonWorkObjIdList), ConstructionWorkBean::getObjId, constructiuonWorkObjIdList)
                .in(CollectionUtils.isNotEmpty(dataPermissionDepartmentOrgIdList), ConstructionWorkBean::getProjectDepartmentObjId, dataPermissionDepartmentOrgIdList)
                .in(CollectionUtils.isNotEmpty(workIdList), ConstructionWorkBean::getObjId, workIdList)
                .eq(ConstructionWorkBean::getStatus, BaseCodeConstants.CodeType_ConstructionStatus.KEY_ConstructionStatus01)
                .orderByAsc(ConstructionWorkBean::getCreateTime)
                .orderByAsc(ConstructionWorkBean::getObjId)
                .list();
        List<ConstructionWorkListVO> workListVOList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(constructionWorkBeanList)) {
            constructionWorkBeanList.forEach(constructionWorkBean -> {
                ConstructionWorkListVO workListVO = new ConstructionWorkListVO();
                workListVO.setConstructionWorkObjId(constructionWorkBean.getObjId());
                workListVO.setConstructionWorkName(constructionWorkBean.getWorkName());
                workListVOList.add(workListVO);
            });
        }

        return workListVOList;
    }

    /**
     * 根据工程ID查询工程名称
     *
     * @param constructionWorkIdList 工程ID
     * @return 工程名称
     */
    @Override
    public List<String> findNameByObjIdList(List<String> constructionWorkIdList) {
        List<ConstructionWorkBean> constructionWorkBeanList = this.lambdaQuery().in(ConstructionWorkBean::getObjId, constructionWorkIdList).list();
        if (CollectionUtils.isNotEmpty(constructionWorkBeanList)) {
            return constructionWorkBeanList.stream().map(ConstructionWorkBean::getWorkName).distinct().collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 根据用户所属单位查询工程列表
     *
     * @return 工程
     */
    @Override
    public List<ConstructionWorkListVO> findWorkListByOrgId() throws GeneralSimpleException {
        List<ConstructionWorkListVO> workListVOList = Lists.newArrayList();
        //查询是否具有总部管理员角色
        boolean headOffice = userService.checkHeadOffice();
        List<String> orgIdList = null;
        boolean generalContractingUnit = false;
        List<String> workIdList = Lists.newArrayList();
        if (!headOffice) {

            //当前用户不具备总部管理员的角色
            String orgId = BaseCommonUtils.extractOrdIdByToken();
            if(StringUtils.isBlank(orgId)){
                log.info("单位信息不存在");
                throw new GeneralSimpleException("100003");
            }
            
            // 是否项目部管理员,如果是项目部管理员，优先以项目部管理员权限为主
            boolean projectDepartment = userService.checkProjectDepartment();
            if(!projectDepartment){
                // 是否总包单位管理员
                generalContractingUnit = userService.checkGeneralContractingUnit();
                if(generalContractingUnit){
                    
                    workIdList = findGeneralContractingUnitAccessWorkId();
                    if(CollectionUtils.isEmpty(workIdList)){
                        return Lists.newArrayList();
                    }
                }
            }
            
            if(!generalContractingUnit){
                orgIdList = orgService.getDataPermissionOrgId();
                if(CollectionUtils.isEmpty(orgIdList)){
                    return Lists.newArrayList();
                }
            }
        }
        List<ConstructionWorkBean> constructionWorkBeanList;
        if(!generalContractingUnit){
            constructionWorkBeanList = this.lambdaQuery().
                    in(!headOffice && CollectionUtils.isNotEmpty(orgIdList),ConstructionWorkBean::getProjectDepartmentObjId, orgIdList)
                    .list();
        }else{
            constructionWorkBeanList = this.lambdaQuery().
                    in(CollectionUtils.isNotEmpty(workIdList), ConstructionWorkBean::getObjId, workIdList)
                    .list();
        }
        
        if (CollectionUtils.isNotEmpty(constructionWorkBeanList)) {
            constructionWorkBeanList.forEach(constructionWorkBean -> {
                ConstructionWorkListVO constructionWorkListVO = new ConstructionWorkListVO();
                constructionWorkListVO.setConstructionWorkObjId(constructionWorkBean.getObjId());
                constructionWorkListVO.setConstructionWorkName(constructionWorkBean.getWorkName());
                workListVOList.add(constructionWorkListVO);
            });
        }

        return workListVOList;
    }

    /**
     * 根据所属项目部ID查询施工工程
     *
     * @param orgIdList 所属项目部ID
     * @return 施工工程ID
     */
    @Override
    public List<String> findIdByProjectDepartmentObjIdIn(List<String> orgIdList) {
        List<ConstructionWorkBean> constructionWorkBeanList = this.lambdaQuery()
                .in(ConstructionWorkBean::getProjectDepartmentObjId, orgIdList)
                .list();
        if (CollectionUtils.isNotEmpty(constructionWorkBeanList)) {
            return constructionWorkBeanList.stream().map(ConstructionWorkBean::getObjId).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 根据工程ID查询负责人
     *
     * @param constructionWorkObjId 工程ID
     * @return 负责人
     */
    @Override
    public String findSuperintendentByObjId(String constructionWorkObjId) {
        ConstructionWorkBean constructionWorkBean = getById(constructionWorkObjId);
        if (Objects.nonNull(constructionWorkBean)) {
            return constructionWorkBean.getSuperintendent();
        }
        return null;
    }

    /**
     * 查询所有的工程ID
     *
     * @return 工程ID
     */
    @Override
    public List<String> findAllId() {
        return this.baseMapper.findAllId();
    }

    /**
     * 根据参建单位ID查询关联的工程
     *
     * @param unitIdList 参建单位ID
     * @return 工程ID
     */
    @Override
    public List<String> findWorkIdByUnitId(String unitIdList) {
        List<ConstructionWorkUnitRelaBean> unitRelaBeanList = constructionWorkUnitRelaService.lambdaQuery().eq(ConstructionWorkUnitRelaBean::getParticipatingUnitObjId, unitIdList).list();
        if(CollectionUtils.isNotEmpty(unitRelaBeanList)){
            return unitRelaBeanList.stream().map(ConstructionWorkUnitRelaBean::getConstructionWorkObjId).distinct().collect(Collectors.toList());
        }
        return Lists.newArrayList();
    }

    /**
     * 根据工程查询所属单位
     *
     * @param constructionWorkObjId 工程ID
     * @return 单位ID
     */
    @Override
    public String findProjectDepartmentObjIdByObjId(String constructionWorkObjId) {
        ConstructionWorkBean constructionWorkBean = this.getById(constructionWorkObjId);
        if(Objects.nonNull(constructionWorkBean)){
            return constructionWorkBean.getProjectDepartmentObjId();
        }
        return null;
    }

    /**
     * 根据所属单位查询工程信息
     *
     * @param projectDepartmentObjId 单位信息
     * @return 工程ID
     */
    @Override
    public List<String> findWorkIdByProjectDepartmentObjId(String projectDepartmentObjId) {
        List<ConstructionWorkBean> constructionWorkBeanList = this.lambdaQuery().eq(ConstructionWorkBean::getProjectDepartmentObjId, projectDepartmentObjId)
                .list();
        if(CollectionUtils.isNotEmpty(constructionWorkBeanList)){
            return constructionWorkBeanList.stream().map(ConstructionWorkBean::getObjId).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 根据单位查询项目信息，并且根据单位的顺序号排序
     *
     * @param headOffice 是否总部管理员
     * @param orgIdList  单位ID
     * @return 工程信息
     */
    @Override
    public List<ConstructionWorkBean> findByIsHeadOfficeAndProjectDepartmentObjIdInOrderByProjectDepartmentOrgOrderAsc(boolean headOffice, List<String> orgIdList) {
        if(headOffice){
            return this.baseMapper.findByOrderByProjectDepartmentOrgOrderAsc();
        }else{
            return this.baseMapper.findByProjectDepartmentObjIdInOrderByProjectDepartmentOrgOrderAsc(orgIdList);
        }
    }

    /**
     * 根据单位信息查询施工工程ID
     *
     * @param orgIdList 单位信息
     * @return 工程ID
     */
    @Override
    public List<String> findWorkIdByProjectDepartmentObjIdIn(List<String> orgIdList) {
        List<ConstructionWorkBean> constructionWorkBeanList = this.lambdaQuery().in(ConstructionWorkBean::getProjectDepartmentObjId, orgIdList)
                .orderByAsc(ConstructionWorkBean::getCreateTime)
                .orderByAsc(ConstructionWorkBean::getObjId)
                .list();
        if(CollectionUtils.isNotEmpty(constructionWorkBeanList)){
            return constructionWorkBeanList.stream().map(ConstructionWorkBean::getObjId).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 查询项目再建工程列表
     *
     * @return 工程信息
     */
    @Override
    public List<ConstructionWorkListVO> findDepartmentPendingAdmissionList() throws GeneralSimpleException {
        List<String> dataPermissionDepartmentOrgIdList = orgService.getDataPermissionDepartmentOrgId();
        if(CollectionUtils.isEmpty(dataPermissionDepartmentOrgIdList)){
            return Lists.newArrayList();
        }

        List<ConstructionWorkBean> constructionWorkBeanList = this.lambdaQuery()
                .in(ConstructionWorkBean::getProjectDepartmentObjId, dataPermissionDepartmentOrgIdList)
                .eq(ConstructionWorkBean::getStatus, BaseCodeConstants.CodeType_ConstructionStatus.KEY_ConstructionStatus01)
                .orderByAsc(ConstructionWorkBean::getCreateTime)
                .orderByAsc(ConstructionWorkBean::getObjId)
                .list();
        List<ConstructionWorkListVO> workListVOList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(constructionWorkBeanList)) {
            constructionWorkBeanList.forEach(constructionWorkBean -> {
                ConstructionWorkListVO workListVO = new ConstructionWorkListVO();
                workListVO.setConstructionWorkObjId(constructionWorkBean.getObjId());
                workListVO.setConstructionWorkName(constructionWorkBean.getWorkName());
                workListVOList.add(workListVO);
            });
        }

        return workListVOList;
    }

    /**
     * 查询参建单位再建工程列表
     *
     * @return 工程信息
     */
    @Override
    public List<ConstructionWorkListVO> findParticipatingUnitPendingAdmissionList() throws GeneralSimpleException {

        String orgId = BaseCommonUtils.extractOrdIdByToken();
        if (StringUtils.isBlank(orgId)) {
            throw new GeneralSimpleException("100003");
        }
        List<String> workIdList = constructionWorkUnitRelaService.findWorkIdByUnitId(orgId);    
        
        if (CollectionUtils.isEmpty(workIdList)) {
            // 该参建单位没有关联的工程，因此直接返回
            return Lists.newArrayList();
        }

        List<ConstructionWorkBean> constructionWorkBeanList = this.lambdaQuery()
                .in(CollectionUtils.isNotEmpty(workIdList), ConstructionWorkBean::getObjId, workIdList)
                .eq(ConstructionWorkBean::getStatus, BaseCodeConstants.CodeType_ConstructionStatus.KEY_ConstructionStatus01)
                .orderByAsc(ConstructionWorkBean::getCreateTime)
                .orderByAsc(ConstructionWorkBean::getObjId)
                .list();
        List<ConstructionWorkListVO> workListVOList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(constructionWorkBeanList)) {
            constructionWorkBeanList.forEach(constructionWorkBean -> {
                ConstructionWorkListVO workListVO = new ConstructionWorkListVO();
                workListVO.setConstructionWorkObjId(constructionWorkBean.getObjId());
                workListVO.setConstructionWorkName(constructionWorkBean.getWorkName());
                workListVOList.add(workListVO);
            });
        }

        return workListVOList;
    }

    /**
     * 根据单位查询监理单位所监理的工程，查询工程下的所有参建单位
     *
     * @param orgId  监理单位ID
     * @param workId
     * @return 所有参见单位
     */
    @Override
    public List<String> findParticipatingUnitObjIdBySupervisorUnit(String orgId, String workId) {
        return constructionWorkUnitRelaService.findParticipatingUnitObjIdBySupervisorUnit(orgId, workId);
    }

    /**
     * 根据参建单位ID查询工程所属的项目部
     *
     * @param unitObjId 参见单位ID
     * @return 项目部ID
     */
    @Override
    public List<String> findObjIdByGeneralContractingUnitObjId(String unitObjId) {
        List<String> workIdList = constructionWorkUnitRelaService.findWorkIdByGeneralContractingUnitId(unitObjId);
        if(CollectionUtils.isNotEmpty(workIdList)){
            List<ConstructionWorkBean> constructionWorkBeanList = this.lambdaQuery().in(ConstructionWorkBean::getObjId, workIdList).list();
            if(CollectionUtils.isNotEmpty(constructionWorkBeanList)){
                return constructionWorkBeanList.stream().map(ConstructionWorkBean::getObjId).collect(Collectors.toList());
            }
        }
        return null;
    }

    @Override
    public List<String> findObjIdByGeneralContractingUnitObjId() throws GeneralSimpleException {
        String unitObjId = BaseCommonUtils.extractOrdIdByToken();
        if(StringUtils.isBlank(unitObjId)){
            log.info("单位信息不存在");
            throw new GeneralSimpleException("100003");
        }
        List<String> workIdList = constructionWorkUnitRelaService.findWorkIdByUnitId(unitObjId);
        if(CollectionUtils.isNotEmpty(workIdList)){
            List<ConstructionWorkBean> constructionWorkBeanList = this.lambdaQuery().in(ConstructionWorkBean::getObjId, workIdList).list();
            if(CollectionUtils.isNotEmpty(constructionWorkBeanList)){
                return constructionWorkBeanList.stream().map(ConstructionWorkBean::getObjId).collect(Collectors.toList());
            }
        }
        return null;
    }

    /**
     * 移除单位负责热
     * @param personId 人员ID
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void removeUnitResponsiblePersonByPersonId(String personId) {
        constructionWorkUnitRelaService.removeUnitResponsiblePersonByPersonId(personId);
    }

    /**
     * 查询总包管理员准入工程
     *
     * @return 工程ID
     */
    @Override
    public List<String> findGeneralContractingUnitAccessWorkId() throws GeneralSimpleException {

        String orgId = BaseCommonUtils.extractOrdIdByToken();
        //当前用户不具备总部管理员的角色
        if(StringUtils.isBlank(orgId)){
            log.info("单位信息不存在");
            throw new GeneralSimpleException("100003");
        }
        List<String> workIdList = findObjIdByGeneralContractingUnitObjId(orgId);
        if(CollectionUtils.isEmpty(workIdList)){
            log.info("没有查询到总包的工程");
            return null;
        }
 
        return workIdList;
    }
    
    @Override
    public List<String> findGeneralContractingUnitAccessWorkId(String orgId) {
        List<String> workIdList = findObjIdByGeneralContractingUnitObjId(orgId);
        if(CollectionUtils.isEmpty(workIdList)){
            log.info("没有查询到总包的工程");
            return null;
        }

        return workIdList;
    }
    
    /**
     * 查询总包单位所管辖的参建单位列表
     *
     * @param constructionWorkIdList 工程
     * @return 参建单位
     */
    @Override
    public List<String> findGeneralContractingUnitParticipatingUnitObjIdByObjIdIn(List<String> constructionWorkIdList) {
        
        return constructionWorkUnitRelaService.findGeneralContractingUnitParticipatingUnitObjIdByObjIdIn(constructionWorkIdList);
    }
}
